package com.guigu.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.commonutils.JwtUtils;
import com.guigu.commonutils.MD5;
import com.guigu.servicebase.exceptionhandler.MyCustomeException;
import com.guigu.systemservice.entity.SysAccount;
import com.guigu.systemservice.mapper.SysAccountMapper;
import com.guigu.systemservice.service.SysAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Jane
 * @since 2024-09-06
 */
@Service
public class SysAccountServiceImpl extends ServiceImpl<SysAccountMapper, SysAccount> implements SysAccountService {

    @Override
    public String queryByNameAndPass(String loginName, String password) {
        if(StringUtils.isEmpty(loginName))
            throw new MyCustomeException(30001, "登录帐号不能为空");
        if(StringUtils.isEmpty(password))
            throw new MyCustomeException(30002, "登录密码不能为空");

        QueryWrapper<SysAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", loginName);
        SysAccount sysAccount = this.getOne(wrapper);
        if(sysAccount == null)
            throw new MyCustomeException(30003, "该用户不存在");
        if(!(MD5.encrypt(password).equals(sysAccount.getPassword())))
            throw new MyCustomeException(30004, "用户名或者密码不正确");

        // 将认证成功的用户信息生成token
        String jwtToken = JwtUtils.getJwtToken(sysAccount.getAccountId(), sysAccount.getLoginName());
        return jwtToken;
    }
}
